﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace JcomTesters.Releases
{
    [jDesc("字符串查找",ok:true,args:new[] { "debug","-debug", "忽略文件", "!f:xx.x", "忽略目录", "!d:xxx", "忽略", "!:xxx  !xxx", "完整路径", "-full"
        , "文件过滤", "-f:xxx -f:\\.txt 用正则", "级数", "-l:10 -level:1 ","[empty1]","查找的内容，不用正则"//,"-case ig",""
    })]
    class StrFindCmd : Ab1Tester
    {
        public override void Run(string[] args)
        {
            //
            //参考 findTester
            //
            //
            //cmd>strfind jfisd -l:2 -n:100
            //
            //var fiType = 0;//全部
            var exps0 = new List<string>();
            var exps1 = new List<string>();
            var exps2 = new List<string>();
            var level0 = 999999;
            var full0 = false;
            var patVal = "";//文件内容过滤
            var filept = "";//文件过滤
            var total_ns = new[] { 0, 0, 0 }; //0 所有文件 1所有目录 2成功匹配
            const int dyn_file = 0;
            const int dyn_dir = 1;
            const int dyn_success = 2;
            foreach (var agitem in args)
            {
                if (agitem.Equals("-debug")) { isDebug = true; }
                //else if (agitem.StartsWith(":d", StringComparison.CurrentCultureIgnoreCase)) { fiType = 1; }
                //else if (agitem.StartsWith(":f", StringComparison.CurrentCultureIgnoreCase)) { fiType = 2; }
                else if (agitem.StartsWith("!d:", StringComparison.CurrentCultureIgnoreCase)) { exps1.Add(agitem.Substring(3)); }
                else if (agitem.StartsWith("!f:", StringComparison.CurrentCultureIgnoreCase)) { exps2.Add(agitem.Substring(3)); }
                else if (agitem.StartsWith("!:")) { exps0.Add(agitem.Substring(2)); }
                else if (agitem.StartsWith("!")) { exps0.Add(agitem.Substring(1)); }
                //
                else if (agitem.Equals("-full")) { full0 = true; }
                else if (agitem.StartsWith("-f:", StringComparison.CurrentCultureIgnoreCase)) { filept = agitem.Substring(3); }
                else if (agitem.StartsWith("-l:", StringComparison.CurrentCultureIgnoreCase)) { level0 = int.Parse(agitem.Substring(3)); }
                else if (agitem.StartsWith("-level:", StringComparison.CurrentCultureIgnoreCase)) { level0 = int.Parse(agitem.Substring(7)); }
                else if (agitem.StartsWith("-")) { continue; }
                else { patVal = agitem; }
            }

            var dir1 = System.IO.Directory.GetCurrentDirectory();
            var di = new System.IO.DirectoryInfo(dir1);
            //
            doWhenPatten("workdir: " + dir1 + (dir1.EndsWith("\\") ? "" : "\\"));
            if (true)//debug0
            {
                Console.WriteLine("patVal: " + patVal);
                Console.WriteLine("filept: " + filept);
            }
            Console.WriteLine();
            //
            var dis1 = di.GetDirectories();
            var wlist = new Queue<System.IO.DirectoryInfo>();
            wlist.Enqueue(di);
            //
            var dpTp_N = 1; var dpTp_i = 0;//深度控制-临时变量
            //
            while (wlist.Count > 0)
            {
                //
                var witem = wlist.Dequeue();
                //
                //深度控制
                if (dpTp_i >= dpTp_N) { level0 -= 1; dpTp_N = wlist.Count; dpTp_i = 0; }
                if (level0 < 0) { break; }
                //
                var files = witem.GetFiles();
                foreach (var fitem in files)
                {
                    total_ns[dyn_file]++;
                    //文件
                    var rst0 = lookupContent(fitem, patVal, filept, new[] { exps0, exps1, exps2 }, isDebug);
                    if (rst0 == 0)
                    {
                        total_ns[dyn_success]++;
                        doWhenPatten(full0 ? fitem.FullName : fitem.FullName.Substring(dir1.Length + 1));
                    }
                }
                var dirs = witem.GetDirectories();
                foreach (var ditem in dirs)
                {
                    total_ns[dyn_dir]++;
                    //目录
                    var rgIc = RegexOptions.IgnoreCase;
                    //存在忽略的，就跳过
                    if (exps0.Where(x => Regex.IsMatch(ditem.Name, x, rgIc)).Any() || exps1.Where(x => Regex.IsMatch(ditem.Name, x, rgIc)).Any())
                    {
                        if (isDebug) Console.WriteLine("dir pass " + ditem.Name);

                        continue;
                    }
                    //var rst0 = vCkContent(1, ditem.Name, patVal, new[] { exps0, exps1, exps2 }, debug0);
                    //if (rst0 == 2)
                    //    continue;
                    wlist.Enqueue(ditem);
                    //if (rst0 == 0)
                    //{
                    //    total_ns[dyn_success]++;
                    //    var pt_ph = ditem.FullName + (ditem.FullName.EndsWith("\\") ? "" : "\\");
                    //    doWhenPatten(full0 ? pt_ph : pt_ph.Substring(dir1.Length + 1));
                    //}
                }
                //
                //深度控制
                dpTp_i++;
            }
            doWhenPatten("\r\n" + "total-info files: " + total_ns[dyn_file] + " finds: " + total_ns[dyn_success]);
        }
        int lookupContent(FileInfo filei, string contentPt, string filept, List<string>[] exps, bool debug0)
        {
            var all_content = System.IO.File.ReadAllText(filei.FullName);

            var exps0 = exps[0];
            var exps1 = exps[1];
            var exps2 = exps[2];
            var rgIc = RegexOptions.IgnoreCase;
            //if (debug0) Console.WriteLine("");
            //文件名匹配
            if (!exps0.Where(x => Regex.IsMatch(filei.Name, x, rgIc)).Any() && !exps2.Where(x => Regex.IsMatch(filei.Name, x, rgIc)).Any())
            {
                if (Regex.IsMatch(filei.Name, filept))
                {
                    //var rst = Regex.IsMatch(all_content, contentPt) ? 0 : 1;
                    //var rst = all_content.IndexOf(contentPt.Replace("\\r\\n", "\r\n").Replace("\\n", "\r\n")) != -1 ? 0 : 1;
                    //匹配，暂时不分大小写
                    var rst = all_content.IndexOf(contentPt.Replace("\\r\\n", "\r\n").Replace("\\n", "\r\n")
                        ,StringComparison.CurrentCultureIgnoreCase) != -1 ? 0 : 1;
                    if (debug0) Console.WriteLine("file0 " + rst + " " + filei.Name);
                    return rst;
                }
                if (debug0) Console.WriteLine("file1 1 " + filei.Name + " filept pass");
                //忽略文件不存在文件名,就正确0
                //return 0;
            }
            if (debug0) Console.WriteLine("file1 1");
            return 1;
        }
        void doWhenPatten(string text)
        {
            Console.WriteLine(text);
        }
    }
}
